import React from 'react';
import {
  View,
  ScrollView,
  TouchableOpacity,
  Platform,
  Alert,
} from 'react-native';
import {Text, Button, ListItem} from '@rneui/base';
import {
  useDebounceEffect,
  useMap,
  useMount,
  useSafeState,
  useSetState,
  useUpdateEffect,
} from 'ahooks';
import {round} from 'lodash';
import style from './style.less';
import {
  requestMultiple,
  checkMultiple,
  PERMISSIONS,
  RESULTS,
  openSettings,
  request,
} from 'react-native-permissions';
import {useNavigation} from '@react-navigation/native';
import {MapPowerResult, MapPowerName} from '@/config/power';
import {CkPowerWaitMs} from '@/config/common';
import dayjs from 'dayjs';
import {useSelector, useDispatch} from 'react-redux';

export default ({children, pagePowers = [], ...otherProps}) => {
  const navigation = useNavigation();
  const appRunState = useSelector(state => state.appRunState.value);

  const [allowPowers, setAllowPowers] = useSafeState([]);
  const [group, setGropu] = useSafeState([]);
  const [unavailablePowers, setUnavailablePowers] = useSafeState([]);

  const setInfo = async () => {
    const newMap = new Map();
    for (const name of new Set(pagePowers)) {
      const key = PERMISSIONS.ANDROID[name] || name;
      newMap.set(key, {name: name});
    }
    const powerList = [...newMap].map(([key]) => key);
    try {
      const statuses = await checkMultiple(powerList);
      for (const [key, powerStr] of Object.entries(statuses)) {
        const oldData = newMap.get(key);
        newMap.set(key, {...oldData, powerStr});
      }

      const getPowersArr = targetValue => {
        const items = [];
        [...newMap].forEach(([, item]) => {
          if (item.powerStr === targetValue) {
            items.push(item);
          }
        });
        return items;
      };

      const allows = getPowersArr(RESULTS.GRANTED);
      setAllowPowers(allows);

      const unavailables = getPowersArr(RESULTS.UNAVAILABLE);
      setUnavailablePowers(unavailables);

      const gArr = [
        // RESULTS.GRANTED,
        RESULTS.LIMITED,
        RESULTS.DENIED,
        RESULTS.BLOCKED,
        // RESULTS.UNAVAILABLE,
      ];
      const rtArr = [];
      gArr.forEach(targetValue => {
        rtArr.push(getPowersArr(targetValue));
      });
      setGropu(rtArr);
    } catch (e) {
      console.log('获取权限异常', e.message);
    }
  };

  useMount(() => {
    setInfo();
  });
  useDebounceEffect(
    () => {
      if (appRunState === 'active') {
        setInfo();
      }
    },
    [appRunState],
    {wait: 0},
  );

  const AuthorizationList = () => (
    <ScrollView style={style.box}>
      <View style={style.group}>
        {[...allowPowers].map((item, index) => (
          <ListItem key={index} style={{marginTop: 1}}>
            <ListItem.Content>
              <ListItem.Title>{MapPowerName.get(item.name)}</ListItem.Title>
              <Text style={style.remark}>{item.name}</Text>
            </ListItem.Content>

            <View>
              <Text>{MapPowerResult.get(item.powerStr)}</Text>
              <Text style={style.remark}>{item.powerStr}</Text>
            </View>
          </ListItem>
        ))}
      </View>
      {group.map((gRows, gIndex) => (
        <View key={gIndex} style={style.group}>
          {[...gRows].map((item, index) => (
            <ListItem key={index} style={{marginTop: 1}}>
              <ListItem.Content>
                <ListItem.Title>{MapPowerName.get(item.name)}</ListItem.Title>
                <Text style={style.remark}>{item.name}</Text>
              </ListItem.Content>
              <View>
                <Button
                  title="点击授权"
                  size="sm"
                  onPress={async () => {
                    if (
                      [RESULTS.UNAVAILABLE, RESULTS.GRANTED].includes(
                        item.powerStr,
                      )
                    ) {
                      return;
                    }
                    let v = '';
                    let t1 = dayjs();
                    let t2;
                    try {
                      v = await request(PERMISSIONS.ANDROID[item.name]);
                      t2 = dayjs();
                    } catch (e) {
                      Alert.alert('操作失败', e.message);
                      return;
                    }
                    let useMs = t2.diff(t1, 'ms');
                    if (useMs < CkPowerWaitMs && v !== RESULTS.GRANTED) {
                      openSettings().catch(() =>
                        Alert.alert('操作失败', '打开系统设置'),
                      );
                    } else {
                      setInfo();
                    }
                  }}
                />
                <Text style={style.remark}>{item.powerStr}</Text>
              </View>
            </ListItem>
          ))}
        </View>
      ))}

      <View style={style.group}>
        {[...unavailablePowers].map((item, index) => (
          <ListItem key={index} style={{marginTop: 1}}>
            <ListItem.Content>
              <ListItem.Title>{MapPowerName.get(item.name)}</ListItem.Title>
              <Text style={style.remark}>{item.name}</Text>
            </ListItem.Content>

            <View>
              <Text>{MapPowerResult.get(item.powerStr)}</Text>
              <Text style={style.remark}>{item.powerStr}</Text>
            </View>
          </ListItem>
        ))}
      </View>

      <View style={style.group}>
        <View style={[style.item, style.itemNoBorder]}>
          <Text></Text>
          <Text></Text>
        </View>
      </View>
    </ScrollView>
  );

  if (allowPowers.length !== pagePowers.length) {
    return (
      <View style={{flex: 1}}>
        <Text style={{textAlign: 'center', marginTop: 10}}>
          访问该页面需要授于以下权限：
        </Text>
        <AuthorizationList />
      </View>
    );
  }

  return React.cloneElement(children, {...otherProps});
};
